package com.linzm.proxy.dynamic;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Author zimingl
 * @Date 2023/8/21 23:31
 * @Description: TODO
 */
public class DynamicProxy {
    // 使用动态代理
    public static void main(String[] args) {
        RealSubject realSubject = new RealSubject();
        InvocationHandler handler = new ProxyHandler(realSubject);
        Subject proxySubject = (Subject) Proxy.newProxyInstance(RealSubject.class.getClassLoader(), realSubject.getClass().getInterfaces(), handler);
        proxySubject.doSomething();
        Subject proxyObject = getProxyObject(RealSubject.class);
        proxyObject.doSomething();
    }

    public static <T> T getProxyObject(Class<T> tClass) {
        // 有实现接口的 new RealSubject().getClass().getInterfaces()
        return (T) Proxy.newProxyInstance(tClass.getClassLoader(), new RealSubject().getClass().getInterfaces(), new ProxyHandler(new RealSubject()));
    }

    public static <T> T getProxyObject2(Class<T> tClass) {
        // 没有实现接口的
        return (T) Proxy.newProxyInstance(tClass.getClassLoader(), new Class[]{tClass}, new ProxyHandler());
    }
}

// 定义接口
interface Subject {
    void doSomething();
}

// 原始类
class RealSubject implements Subject {
    public void doSomething() {
        System.out.println("RealSubject 执行了某些操作。");
    }
}

// InvocationHandler实现类
class ProxyHandler implements InvocationHandler {
    private Object target;

    public ProxyHandler(Object target) {
        this.target = target;
    }

    public ProxyHandler() {

    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("代理类执行前的逻辑。");
        Object result = method.invoke(target, args);
        System.out.println("代理类执行后的逻辑。");
        return result;
    }
}


